<?php
namespace Admin\Controller;

use Think\Page;

class BannerController extends CommonController
{
    public $model = null;

    public function __construct()
    {
        parent::__construct();
        $this->model = M('banner');
    }

    public function index()
    {
    	$User = M("banner");
    	$banner=$User->select();
    	$this->assign("banner", $banner);
    	$this->display();
    }
    
    /**
     * 添加数据，添加完修改
     */
    public function add()
    {
        if (IS_GET) {

            $this->display();

        } elseif (IS_POST) {
            $data = [
                'parent_id'   => I('post.category_id', '', 'trim'),
                'url'        => I('post.url', '', 'trim'),
                'sort'        => I('post.sort', '', 'intval'),
                'add_time'    => CUR_DATETIME,
            ];

            // 首字母大写，下划线
            // 如：Ad  Ad_Banner（Uploads文件夹名称）
            $result = upload('Category_Image');

            $id = $this->model->add($data);

            if (isset($result['image'])) {
                $this->model
                    ->where(['id' => $id])
                    ->save(['image' => $result['image']['url']]);
            }

            if ($id) {
                $this->success('添加成功', U(CONTROLLER_NAME . '/update', [
                    'id' => $id,
                ]));
            }
        }
    }
    
    public function update()
    {
        if (IS_GET) {

            $id = I('get.id', 0, 'intval');

            $data = $this->model->find($id);
            $this->assign('data', $data);

            $this->display();

        } elseif (IS_POST) {

            $id   = I('post.id', 0, 'intval');
            $data = [
                'parent_id'   => I('post.category_id', '', 'trim'),
                'url'        => I('post.url', '', 'trim'),
                'sort'        => I('post.sort', '', 'intval'),
                'sort'        => I('post.sort', '', 'intval'),
            ];

            // 首字母大写，下划线
            // 如：Ad  Ad_Banner （Uploads文件夹名称）
            $result = upload('Category_Image');
            $this->model->where(['id' => $id])->save($data);

            if (isset($result['image'])) {
                $this->model
                    ->where(['id' => $id])
                    ->save(['image' => $result['image']['url']]);
            }

            $this->success('修改成功', U(CONTROLLER_NAME . '/update', [
                'id' => $id,
            ]));
        }
    }
   
}
